<?php

namespace App\Http\Controllers;

use App\Mall;
use App\Order;
use App\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Traits\CheckPermissions;

class OrderRecycleController extends Controller
{
    use CheckPermissions;
    //回收站主页
    public function index($mall_id)
    {
        $this->is_mall_manager($mall_id);
        $mall_name = Mall::find($mall_id)->name;
        $orders = Order::onlyTrashed()->where('mall_id', $mall_id)->paginate(10);
        foreach ($orders as $key => $value) {
            $pros = json_decode($value->products);
            foreach ($pros as $k => $val) {
                $orders[$key]['pro_text'] .= '['.$val->product->name.'×'.$val->total_num.']';
            }
        }
        return view('admin.recycle.index', compact('mall_id', 'mall_name', 'orders'));
    }

    //恢复订单
    public function back_order(Request $request)
    {
        $order_id = $request->input('order_id');
        try {
            $order = Order::onlyTrashed()->find($order_id);
            $mall_id=$order->mall_id;
            $this->is_mall_manager($mall_id);
            DB::transaction(function () use ($order) {
                $products = json_decode($order->products, true);
                foreach ($products as $product) {
                    $this_product = Product::find($product['product']['id']);
                    if (!is_null($this_product)) {
                        //减库存
                        $this_product->decrement('stock', $product['total_num']);
                        if ($this_product->stock < 0) {
                            throw new \Exception('商品'.$this_product->name.'库存不足!');
                        }
                    } else {
                        throw new \Exception('商品'.$product['product']['name'].'不存在');
                    }
                }
                $order->restore();
            }, 5);
        } catch (\Exception $exception) {
            return back()->with('success', '恢复失败'.$exception->getMessage());
        }
        return back()->with('success', '恢复成功.');
    }

    //删除超过15天的订单
    public function destroy()
    {
        $del = Order::onlyTrashed()->where('deleted_at', '<', now()->subDay(15))->delete();
        if ($del) {
            return back()->with('success', '删除超过15天的订单成功');
        } else {
            return back()->with('success', '没有过期订单被删除!!');
        }

    }
}
